/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.guit.demo.client.login;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.inject.Inject;

import com.guit.client.GuitPresenter;
import com.guit.client.apt.GwtPresenter;
import com.guit.client.binder.GuitBinder;
import com.guit.client.binder.ViewField;
import com.guit.client.binder.ViewHandler;
import com.guit.client.binder.contributor.KeyCode;
import com.guit.client.binder.contributor.RunAsync;
import com.guit.client.dom.Input;
import com.guit.client.dom.Span;
import com.guit.client.place.Place;
import com.guit.demo.client.login.LoginPresenter.LoginBinder;
import com.guit.demo.client.main.MainPresenter;

@RunAsync
@GwtPresenter(placeName = "login")
public class LoginPresenter extends GuitPresenter<LoginBinder> implements Place<Void> {

  public interface LoginBinder extends GuitBinder<LoginPresenter> {
  }

  public static final String ERROR_LOGGIN_IN = "Error loggin in!";

  public static final String YOU_LOGGED_IN = "You logged in!";

  private final MainPresenter hasContent;

  @ViewField
  Input username;

  @ViewField
  Input password;

  @ViewField
  Span message;

  @Inject
  public LoginPresenter(MainPresenter hasContent) {
    this.hasContent = hasContent;
  }

  @ViewHandler
  void clear$click() {
    username.text(null);
    password.text(null);
    message.text(null);
    username.focus();
  }

  @Override
  public void go(Void data) {
    hasContent.setContent(getView(), 0);
  }

  @ViewHandler
  void login$click() {
    tryLogin();
  }

  @ViewHandler
  @KeyCode({KeyCodes.KEY_ENTER})
  void login$keyPress() {
    tryLogin();
  }

  @ViewHandler
  @KeyCode({KeyCodes.KEY_ENTER})
  void username$password$keyPress() {
    tryLogin();
  }

  private void tryLogin() {
    if ("admin".equals(username.text()) && "admin".equals(password.text())) {
      message.text(YOU_LOGGED_IN);
      username.style("border", "");
      password.style("border", "");
    } else {
      message.text(ERROR_LOGGIN_IN);
      username.style("border", "1px solid red");
      password.style("border", "1px solid red");
    }
  }
}
